<?php
/**
 * 出借记录
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/7/9
 * Time: 9:27
 */
namespace app\admin\controller;

use think\App;
use think\Request;

class Lend extends Common
{
    public function __construct(App $app = null)
    {
        parent::__construct($app);

    }

    /**
     * 出借列表页面
     * @return mixed
     */
    public function listUI(){
        return $this->fetch('list');
    }

    /**
     * 归还页面
     * @return mixed
     */
    public function revertUI(){

        $tools = db('tools_lend_record')->where('lend_id',input('id'))->where('is_return',0)->select();
        return $this->fetch('revert',['tools'=>$tools]);
    }

    /**
     * 出借
     * @return mixed
     */
    public function outLendUI(){

        $pid = db('admin')->where('admin_id',session('aid'))->find();

        if($pid['group_id'] != 8){
            $this->error('请使用工具管理员账号操作');
        }

        $tools = db('tools')->where(['admin_id'=>$pid['a_pid'],'state_id'=>30])->select();

        $en = db('admin')->where(['a_pid'=>$pid['a_pid'],'group_id'=>5])->select();

        return $this->fetch('out',['tools'=>$tools,'en'=>$en]);
    }

    /**
     * 出借记录
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function queryPage(Request $request){
        $input = $request->param();
        $gid = session('gid');
        if($gid == 8){
            $info = db('admin')->where('admin_id',session('aid'))->find();
            $input['admin_id'] = $input['a_pid'];
        }else if($gid == 1){

        }

        $rows = db('tools_lend')->alias('tl')
            ->order('tl.id desc')
                ->where(function ($query)use($input){
                    if(!empty($input['admin_id']))
                        $query->where('tl.admin_id',$input['admin_id']);
                    if(!empty($input['state_id']))
                        $query->where('tl.state_id',$input['state_id']);
                    if(!empty($input['out_name']))
                        $query->where('tl.out_name','LIKE','%'.$input['out_name'].'%');
                    if(!empty($input['input_name']))
                        $query->where('tl.input_name','LIKE','%'.$input['input_name'].'%');
                })
            ->join('admin a','a.admin_id=tl.admin_id','left')
            ->join('state st','st.id=tl.state_id','left')
            ->field(['tl.*','a.username','a.name','st.state_name'])
            ->paginate($input['limit'])->toArray();
        return ['code'=>0,'msg'=>'获取成功!','data'=>$rows['data'],'count'=>$rows['total'],'rel'=>1];
    }

    /**
     * 创建出借单
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add(Request $request){

        if(session('gid') != 8){
            return ['code'=>0,'msg'=>'请使用工具管理员账号创建出借单'];
        }

        $input = $request->only(['out_name','input_id','desc']);

        $ids = $request->param('ids');

        $info = db('admin')->where('admin_id',$input['input_id'])->find();
        $input['input_name'] = $info['name'].'('.$info['username'].')';
        $input['out_id'] = session('aid');
        $arr = explode(',',$ids);
        if(count($arr)<=0){
            return ['code'=>0,'msg'=>'请选择工具'];
        }
        $pid = db('admin')->where('admin_id',session('aid'))->find();
        $input['admin_id'] = $pid['a_pid'];
        $row = db('tools_lend')->insertGetId($input);
        if($row){
            $tli = db('tools')->where('id','in',$arr)->field(['id','title','model'])->select();
            $det = [];
            foreach ($tli as $v){
                $det[] = [
                    'tools_id'=>$v['id'],
                    'tools_name'=>$v['title'].'-'.$v['model'],
                    'lend_id'=>$row,
                    'lend_id'=>$row,
                ];
            }
            db('tools_lend_record')->insertAll($det);
            db('tools')->where('id','in',$arr)->update(['state_id'=>31]);


            //这里发送模板消息


            return ['code'=>1,'msg'=>'出借成功'];
        }else{
            return ['code'=>0,'msg'=>'创建出借单失败'];
        }

    }

    /**
     * 借用工具列表
     * @param Request $request
     * @return array
     */
    public function toolsList(Request $request){
        $lid = $request->param('id');
        if(empty($lid)) return ['code'=>0,'msg'=>'id参数错误'];
        $rows = db('tools_lend_record')
            ->alias('tr')
            ->order('tr.id desc')
            ->where('tr.lend_id',$lid)
            ->join('state s','s.id=tr.state_id','left')
            ->field(['tr.*','s.state_name'])
            ->select();
        return ['code'=>1,'msg'=>'获取成功','data'=>$rows];
    }

    /**
     * 工具归还
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function revert(Request $request){
        if(session('gid') != 8){
            return ['code'=>0,'msg'=>'请使用工具管理员账号归还工具'];
        }

        $input = $request->param();

        if(empty($input['id'])) return ['code'=>0,'msg'=>'id参数错误'];

        $arr = [];
        $a1 = [];//正常的
        $a2 = [];//损坏的
        $a3 = [];//丢失的
        foreach ($input['ids'] as $v){
            $arr[] = $v['id'];
            if($v['state_id'] == '30'){
                $a1[] = $v['id'];
            }else if($v['state_id'] == '33'){
                $a2[] = $v['id'];
            }else if($v['state_id'] == '34'){
                $a3[] = $v['id'];
            }
        }

        $up = [
            'return_time'=>date('Y-m-d H:i:s',time()),
            'return_name'=>$input['return_name'],
            'desc'=>$input['desc'],
            'is_return'=>1,
        ];

        if(count($a1)>0)
            $row = db('tools_lend_record')->where('lend_id',$input['id'])->where('tools_id','in',$a1)->update($up);

        if(count($a2)>0){
            $up['state_id'] = 33;
            $row = db('tools_lend_record')->where('lend_id',$input['id'])->where('tools_id','in',$a2)->update($up);
        }

        if(count($a3)>0){
            $up['state_id'] = 34;
            $row = db('tools_lend_record')->where('lend_id',$input['id'])->where('tools_id','in',$a3)->update($up);
        }


        if($row){
            $count = db('tools_lend_record')->where('lend_id',$input['id'])->where('is_return',0)->count();
            if($count<=0){
                $sid = 42;
            }else{
                $sid = 41;
            }

            db('tools_lend')->where('id',$input['id'])->update(['state_id'=>$sid]);

            if(count($a1)>0)
                db('tools')->where('id','in',$a1)->update(['state_id'=>30]);
            if(count($a2)>0)
                db('tools')->where('id','in',$a2)->update(['state_id'=>33]);
            if(count($a3)>0)
                db('tools')->where('id','in',$a3)->update(['state_id'=>34]);


            //这里发送模板消息



            return ['code'=>1,'msg'=>'工具归还成功'];
        }else{
            return ['code'=>0,'msg'=>'工具归还操作失败'];
        }
    }

    /**
     * 出借单作废
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function toVoid(Request $request){
        $id = $request->param('lend_id');

        $info = db('tools_lend')->where('id',$id)->find();
        if($info['is_var'] != 0){
            return ['code'=>0,'msg'=>'该出借单已确认，不可作废'];
        }

        $row = db('tools_lend')->where('id',$id)->update(['state_id'=>43]);

        if($row){

            $row = db('tools_lend_record')->where('lend_id',$id)->field(['tools_id'])->select();

            $ids = [];
            foreach ($row as $v){
                $ids[] = $v['tools_id'];
            }
            db('tools')->where('id','in',$ids)->update(['state_id'=>30]);
            db('tools_lend_record')->where('lend_id',$id)->update(['state_id'=>43]);
            //发送模板消息


            return ['code'=>1,'msg'=>'该出借单已成功作废'];
        }

        return ['code'=>0,'msg'=>'操作失败'];
    }


}